<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深拷贝</title>
</head>

<body>
    <h1>深拷贝</h1>
    <ul>
        <li>
            <b>扩展运算符</b>
            <p>这个方法只能实现第一层的拷贝，当有多层的时候还是浅拷贝</p>
        </li>
        <li>
            <b>JSON.parse(JSON.stringify())</b>
            <p>该方法不能拷贝内部函数</p>
        </li>
        <li>利用递归函数实现</li>
    </ul>
    <script>
        // 1. 拓展运算符
        let obj = {
            name: 'lee',
            age: 18,
            func: function () {
                console.log(this);
            },
            info: {
                a1: 123,
                a2: {
                    b2: 123
                }
            },
            arr: [[1,2], 2, 4, 3]
        }
        let obj1 = { ...obj }
        obj1.name = 'tom'
        obj1.func()
        console.log(obj1);

        // JSON.parse(JSON.stringify())
        let obj2 = JSON.parse(JSON.stringify(obj))
        obj2.name = 'avery'
        console.log(obj2);

        // 递归函数
        function exten(origin, deep) {
            let obj = {}
            if (origin instanceof Array) {
                obj = []
            }
            for (let key in origin) {
                let value = origin[key]
                obj[key] = (!!deep && typeof value === 'object' && value !== null) ? exten(value, deep) : value
            }

            return obj
        }

        const obj3 = exten(obj, true)
        obj3.arr[0].push(888)
        console.log(obj3);
    </script>
</body>

</html>